package com.zh.client.cart.controller;

import com.zh.client.products.service.ProductsService;
import com.zh.pojo.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/client/cart")
public class CartController {
    @Autowired
    ProductsService productsService;

    @RequestMapping("/addCart")
    public String addCart(String id, HttpSession session){
        Products products = productsService.findProductById(id);
        //创建购物车
        Map<Products,Integer> cart = (Map<Products, Integer>) session.getAttribute("cart");
        if(cart == null){
            cart = new HashMap<>();
        }
        //把商品加入到购物车，数量为1
        if(null != cart.get(products) && cart.get(products) != 0){
            if(cart.get(products)>=products.getPnum()){
                cart.put(products,cart.get(products));
            }else {
                cart.put(products,cart.get(products)+1);
            }
        }else {
            cart.put(products,1);
        }
        session.setAttribute("cart",cart);
        return "redirect:/client/cart.jsp";
    }

    //改变商品数量
    @RequestMapping("/changeCart")
    public String changeCart(String id,Integer count,HttpSession session){
        //获取改变数量的商品信息
        Products products = productsService.findProductById(id);
        //从session中获取购物车
        Map<Products,Integer> cart = (Map<Products, Integer>) session.getAttribute("cart");
        if(count == 0){
            cart.remove(products);
        }else {
            cart.put(products,count);
        }
        return "redirect:/client/cart.jsp";
    }

}
